package cn.ghf.basic.controller;

import cn.ghf.basic.util.AjaxResult;
import cn.ghf.basic.util.FastDfsUtil;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
@Api(tags = "FastDfs",description = "FastDfs")
public class FastDfsController {

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){
        try {
            //获取原文件名
            String filename = file.getOriginalFilename();
            //获取文件后缀
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            //获取文件上传后的路径
            String path = FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.createAjaxResult().setResultObj(path);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.createAjaxResult().setMsg("上传失败");
        }
    }

    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path") String path){
        try {
            String s = path.substring(1);
            String groupName = s.substring(0, s.indexOf("/"));
            String fileName = s.substring(s.indexOf("/")+1);
            FastDfsUtil.delete(groupName, fileName);
            return AjaxResult.createAjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.createAjaxResult().setMsg("删除失败");
        }
    }
}
